package com.aaa.test.service;

import com.aaa.test.entity.Permission;
import com.aaa.test.entity.Users;
import com.aaa.test.mapper.PermissionMapper;
import com.aaa.test.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName MyUserService
 * @Description TODO
 * @Aythor WYX
 * @Date 2022/11/2 17:07
 * Version 1.0
 **/
@Service
public class MyUserService implements UserDetailsService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UsersMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users=userMapper.selectByUsername(username);
        if (users!=null){
            Collection<GrantedAuthority> authorities=new ArrayList<>();
            List<Permission> permissions=permissionMapper.findByUserid(users.getUserid());

            for(Permission item:permissions){
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item.getPercode());
                authorities.add(simpleGrantedAuthority);
            }
            User user=new User(username,users.getUserpwd(),authorities);
            return user;
        }
        return null;
    }
}
